﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Audit.Generators
{
    class DiscreteGenerator : Generator
    {
        private const byte countOfFields = 2;     //count of rows in input args(value, probability)

        /// <summary>
        /// Check input args for current distribution
        ///  -structure of array
        ///  -type of values
        ///  -positivity of values at probability
        ///  -sum of values at probability must be 1
        /// </summary>
        /// <param name="_args">Parametrs for generator</param>
        /// <returns>True if all conditisions are successfull</returns>
        protected override bool ValidateArgs(Array _args)
        {
            return true;
            //try
            //{
            //    bool result = (_args.GetLength(0) == countOfFields);

            //    if (result)
            //    {
            //        int length = _args.GetLength(1);
            //        double[,] args = (double[,])_args;
            //        double sum = 0;

            //        for (int i = 0; i < length; i++)
            //        {
            //            if (args[1, i] > 0)
            //                sum += args[1, i];
            //            else
            //            {
            //                result = false;
            //                break;
            //            }
            //        }

            //        result &= (sum == 1);
            //    }

            //    return result;

            //}
            //catch (Exception err)
            //{
            //    return false;
            //}
        }

        /// <summary>
        /// Generate variables arranged under Discrete distribution
        /// </summary>
        protected override void Generate()
        {
            double[,] sequence = (double[,])Args;

            double[] intervals = new double[sequence.GetLength(1)];

            intervals[0] = sequence[1, 0];
            for (int i = 1; i < intervals.Length; i++)
                intervals[i] = intervals[i - 1] + sequence[1, i];

            Random rand = new Random();
            double element;
            int j;

            for (int i = 0; i < Count; i++)
            {
                j = 0;
                element = rand.NextDouble();

                while (element > intervals[j++]) ;

                Variables[i] = sequence[0, j - 1];
            }


        }

    }
}
